<template>
  <div class="wrapper">
    <div class="sub_title lr_nav_bot_bd">
      <div style="height: var(--lr_status_height);"></div>
      <div class="tit_txt">
        <div class="ic icl">
          <i @click="saveSsjingdu" style="font-size: 19rem; font-weight: bolder;margin-left: 3vw;"
            class="iconfont lricon-baocun1"></i>
        </div>
        <div @click="r">(六壬起个课APP-课例)</div>
        <div @click.stop="async () => {
          await getSscord()
          if (showSscord) {
            showSscord = false
          } else { showSscord = true }
        }" class="ic icr"><i style="font-size: 18rem;margin-right: 3vw;" class="iconfont lricon-gengduo1"></i></div>
      </div>
    </div>
    <div ref="searchBox" class="search_wrapper">
      <div class="left"><i class="iconfont lricon-sousuo" style="font-size: 18rem;"></i>
      </div>
      <input placeholder="输入内容搜索" @keydown="search" type="search" v-model="searchKW" class="mid editable-div"></input>
      <div class="right" @click.stop="onCancelSearch">取消</div>
    </div>
    <div class="sctotal">总共查到<span style="color: red;">{{ totalKelis.length }}</span>条课例</div>
    <div class="keli_content">
      <div @click="toReader(item)" class="keli_item" v-for="(item, index) in currentKelis">
        <div class="xing">{{ item.cunDang.guaShi[0] }}</div>
        <div class="i_content">
          <div class="top">
            <div class="ming">{{ item.cunDang.guaShi.slice(1, 3) }}</div>
           <!-- <i class="iconfont lricon-shoucang"></i> 
           <i class="iconfont lricon-pingbi1"></i> -->
            <div class="sj">{{ item.ganzhiDatetime.year + '-' + item.ganzhiDatetime.month + '-' +
              item.ganzhiDatetime.day + '-' + item.ganzhiDatetime.hour }}</div>
          </div>
          <div class="bot">{{ item.cunDang.zhanShi }}</div>
        </div>
      </div>
      <div class="safe" style="width: 300rem;height: 56rem;"></div>
    </div>
    <div class="pagination_wrapper">
      <div class="pagination_content">
        <nut-pagination @change="changPage" style="background-color: transparent;" :show-page-size="5" v-model="page"
          :total-items="totalLens" :items-per-page="10">
          <template #prev-text>
            <Left width="10px" height="10px" />
          </template>
          <template #next-text>
            <Right width="10px" height="10px" />
          </template>
        </nut-pagination>
      </div>
    </div>
    <van-popup :lock-scroll="false" v-model:show="showSscord" round position="bottom" :style="{ height: '60vh' }">
      <div class="search_cord">
        <div class="tit">
          <div class="btn"></div>
          <div>搜索记录</div>
          <div @click="showSscord = false" class="btn">关闭</div>
        </div>
        <div class="content">
          <div v-for="(item, index) in sscords">
            <van-swipe-cell :disabled="false">
              <div @click="huifuLsss(item)" :class="{ noborder: index == sscords.length - 1 }" class="cord_box">
                <div class="box_r">
                  <i style="font-size: 28rem;" class="iconfont lricon-quanjusousuo"></i>
                </div>
                <div class="box_m">
                  <div class="m_top">{{ item.keyword }}</div>
                  <div class="m_bot"><span>{{ item.date }}</span><span><i style="font-size: 12rem;"
                        class="iconfont lricon-yuedu"></i>阅读{{ item.page }}页</span></div>
                </div>
              </div>
              <template #right>
                <div class="swcr">
                  <i @click="deleteSscord(item.id)" style="font-size: 18rem;" class="iconfont lricon-shanchu1"></i>
                </div>
              </template>
            </van-swipe-cell>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getBookRdP, getCurrentBook } from "../api/ziLiao";
import { getAllATag, getMatchResults, processHightLightHtml } from "../api/bookRead";
import { ColorPicker } from "vue3-colorpicker";
import { onBackKeyDown } from "tauri-plugin-app-events-api";
import Vue3TouchEvents from "vue3-touch-events";
import { Overlay, Progress, Stepper, Switch, Slider, FloatingBubble, Popup, SwipeCell } from "vant";
import { deleteSscord, getSscord, saveSscord, selectGuFaKeLiByKeyword, upDatesscord } from "../api/dbUtils";
import { Pagination, showToast } from '@nutui/nutui'
import { Left, Right } from '@nutui/icons-vue'
import { show } from "@tauri-apps/api/app";
import { useQiKeDateStore } from "../store";
import { formatDatetoymdhms } from "../api/dateUtils";
import { confirm ,open,save} from '@tauri-apps/plugin-dialog';
export default {
  name: "Test",
  components: {
    VanOverlay: Overlay,
    VanProgress: Progress,
    ColorPicker,
    VanStepper: Stepper,
    VanSwitch: Switch,
    VanSlider: Slider,
    NutPagination: Pagination,
    Left,
    Right,
    FloatingBubble,
    VanPopup: Popup,
    VanSwipeCell: SwipeCell,
  },
  data() {
    return {
      searchKW: '',
      showMuLu: false,
      bookResultL: [],
      totalKelis: [],
      page: 1,
      totalLens: 0,
      currentKelis: [],
      showSscord: false,
      qiKeDateStore: useQiKeDateStore(),
      currentSskey: '@',
      sscords: [],
      slcId: 0,
    };
  },
  async created() {


    let r = await selectGuFaKeLiByKeyword(this.currentSskey)
    this.totalKelis = [...r]
    this.totalLens = this.totalKelis.length
    this.changPage(1)
  },

  props: {},
  methods: {
    async searchBookByK() {
      let r = await selectGuFaKeLiByKeyword(this.searchKW)
      this.totalKelis = [...r]
      this.totalLens = r.length
      this.page = 1
      this.changPage(1)
    },
    getRdPercent(tit) {
      return getBookRdP(tit);
    },
    search(event) {
      if (event.key === 'Enter') {
        this.currentSskey = this.searchKW
        this.searchBookByK();
      }
    },
    onCancelSearch() {
      this.searchKW = ''
    },
    toReader(v) {
      this.qiKeDateStore.upDateQiKeDatetimeOption(v);
      this.$router.push("/paipan");
    },
    async huifuLsss(v) {
      this.slcId = v.id
      this.currentSskey = v.keyword
      let r = await selectGuFaKeLiByKeyword(v.keyword)
      this.totalKelis = [...r]
      this.totalLens = this.totalKelis.length
      this.page = v.page
      this.changPage(this.page)
    },
    async saveSsjingdu() {
      if (this.slcId == 0) {
        let ssObj = {}
        ssObj.type = 'qj'
        if (this.currentSskey.includes('#')) {
          ssObj.type = 'jq'
        }
        ssObj.keyword = this.currentSskey;
        ssObj.page = this.page
        ssObj.date = formatDatetoymdhms(new Date())
        let v = await saveSscord(ssObj)
        showToast.success('保存成功', { id: 1, duration: 1500 })
      } else {
        upDatesscord(this.slcId, this.page)
        showToast.success('更新成功', { id: 1, duration: 1500 })
      }      
    },
    async deleteSscord(id) {
      let v = await deleteSscord(id)
      showToast.warn('删除成功', { id: 1, duration: 1500 })
      await this.getSscord()
    },
    async getSscord() {
      let result = await getSscord();
      this.sscords = [...result];
    },
    changPage(value) {
      // alert(value)
      let r = this.paginateArray(this.totalKelis, value, 10).data
      this.currentKelis = [...r]
    },
    paginateArray(array, pageNum = 1, pageSize = 10) {
      // 处理参数边界值
      const currentPage = Math.max(1, Math.floor(Number(pageNum))); // 确保页码为正整数
      const size = Math.max(1, Math.floor(Number(pageSize))); // 确保每页条数为正整数
      const total = array.length; // 总记录数

      // 计算总页数（向上取整）
      const totalPages = Math.ceil(total / size);

      // 处理页码超出范围的情况（如果页码大于总页数，返回最后一页）
      const validPage = Math.min(currentPage, totalPages || 1);

      // 计算当前页数据的起始索引和结束索引
      const startIndex = (validPage - 1) * size;
      const endIndex = startIndex + size;

      // 截取当前页数据
      const currentPageData = array.slice(startIndex, endIndex);

      // 返回分页信息
      return {
        data: currentPageData,       // 当前页的数据
        pageNum: validPage,          // 当前页码（经过有效性处理）
        pageSize: size,              // 每页条数
        total: total,                // 总记录数
        totalPages: totalPages       // 总页数
      };
    }
  },
  mounted() {
  },
  directives: {
    ...Vue3TouchEvents.directives,
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  height: 100vh;
  width: 100vw;
  background-color: var(--lr_lcbgc);
  position: fixed;
  display: flex;
  flex-direction: column;
  top: 0;
  align-items: center;
  left: 0;
  .sub_title {
    width: 100vw;
    background-color: var(--nav_bg_color);
    display: flex;
    align-items: center;
    flex-direction: column;

    .tit_txt {
      .ic {
        i {
          font-size: 20px;

          &:active {
            transition: transform 0.3s ease;
            transform: scale(1.2)
          }
        }

        text-align: center;
        width: 20vw;
        // background-color: #531c1c;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .icl {
        // background-color: #b34747;
        text-align: left;
        font-size: 18px;

        justify-content: flex-start;
      }

      .icr {
        // background-color: #34cc23;
        text-align: right;
        font-weight: bolder;
        justify-content: flex-end;
      }

      width: 94vw;
      height: 30px;
      line-height: 30px;
      font-size: 18px;
      font-weight: 600;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .sctotal {
    width: 92vw;
    height: 29rem;
    line-height: 29rem;
    font-size: 17.5rem;
    margin-top: 4rem;
    font-weight: 600;
  }

  .search_wrapper {
    border: 2rem solid var(--cart_bg_color);
    display: flex;
    align-items: center;
    margin-top: 8rem;
    height: 30rem;
    width: 90vw;
    //  background-color: #634a5b;
    border-radius: 17rem;
    line-height: 36rem;

    .left {
      width: 31rem;
      height: 24rem;
      line-height: 24rem;
      text-align: center;
      font-size: 18rem;
    }

    input {
      background-color: #ffffff;
      border: none;
      outline: none;
      height: 30rem;
    }

    input::-webkit-search-cancel-button {
      display: none;
    }

    .mid {
      width: calc(94vw - 84rem);
      font-size: 16rem;
      overflow-x: auto;
      // white-space: nowrap;
      /* 禁止文本换行 */
      overflow-x: auto;
      /* 内容超出时显示水平滚动条 */
      overflow-y: hidden;
      /* 隐藏垂直滚动条 */

      /* 设置固定宽度 */
      /* 可选：平滑滚动效果 */
      scroll-behavior: smooth;
    }

    .right {
      width: 36rem;
      height: 24rem;
      line-height: 24rem;
      text-align: center;
      font-size: 13rem;
      background-color: var(--cart_bg_color);
      border-radius: 12rem;
      margin-right: 3rem;
      margin-left: 8rem;
      color: white;
      padding-left: 3rem;
      padding-right: 3rem;
    }

    .right:active {
      transition: transform 0.3s ease;
      transform: scale(1.2)
    }

    .editable-div {
      // border: 1px solid #ddd;
      border-radius: 6px;
      /* 确保有足够编辑空间 */
      outline: none;
      /* 移除默认聚焦边框 */
    }

    /* 聚焦时的样式 */
    // .editable-div:focus {
    //   border-color: #3B82F6;
    //   box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
    // }
  }

  .keli_content {
    margin-top: 10rem;
    width: fit-content;
    width: 92vw;
    // background-color: #da1616;
    flex-shrink: 0;
    overflow: scroll;
    height: calc(100vh - var(--safe-top) - 170rem);


    .keli_item {

      width: 92vw;
      height: fit-content;
      margin-bottom: 10rem;
      align-items: center;
      display: flex;

      .xing {
        border-radius: 50%;
        background-color: #E91E63;
        color: #ffffff;
        height: 40rem;
        width: 40rem;
        line-height: 40rem;
        text-align: center;
        font-size: 18rem;
      }

      .i_content {
        // background-color: whitesmoke;
        margin-left: 10rem;
        width: calc(92vw - 50rem);
        height: fit-content;
        display: flex;
        border-radius: 6rem;
        flex-direction: column;

        .top {
          font-size: 15rem;

          .ming {
            font-weight: bold;
          }

          height: 25rem;
          line-height: 25rem;
          width: 100%;
          display: flex;
          justify-content: space-between;

          .sj {
            color: #7B1FA2;
            color: #880E4F;
          }
        }

        .bot {
          line-height: 20rem;
          height: fit-content;
          width: 100%;
          color: #002c1c;
          font-size: 14rem;
          overflow: scroll;
        }
      }
    }
  }

  .pagination_wrapper {
    position: fixed;
    bottom: calc(var(--lr_nav_height) + 20rem);
    height: 36rem;
    width: 100vw;
    display: flex;
    justify-content: center;
    background-color: transparent;

    .pagination_content {
      width: fit-content;
      height: 36rem;
      border-radius: 18rem;
      // background-color: var(--cart_bg_color);
      overflow: hidden;
      background-color: transparent;

      ::v-deep(.nut-pagination-item) {
        height: 36rem;
        width: 40rem;
        margin-left: 1px !important;
        margin-right: 1px !important;
        border: none !important;
        border-radius: 0;
        background-color: var(--cart_bg_color);
      }

      ::v-deep(.nut-pagination-contain) {
        margin-left: 1rem;
        margin-right: 0;
        display: flex;
        justify-content: space-between;
      }

      ::v-deep(.nut-pagination) {
        display: flex;
        justify-content: center;
      }

      ::v-deep(.nut-pagination-prev) {
        height: 36rem;
        width: 40rem;
        margin-right: 1px;
        border-left: none;
        border-top: none;
        border-bottom: none;
        padding: 0;
        border-radius: 0;
        background-color: var(--cart_bg_color);
      }

      ::v-deep(.nut-pagination-next) {
        height: 36rem;
        width: 40rem;
        padding: 0;
        margin-left: 1px;
        border-right: none;
        border-top: none;
        border-bottom: none;
        border-radius: 0;
        background-color: var(--cart_bg_color);
      }
    }
  }

  .search_cord {
    height: calc(60vh - 54rem);
    width: 100vw;
    display: flex;
    flex-direction: column;
    margin-bottom: 54rem;
    .tit {
      width: 100vw;
      height: 45rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 16rem;
      font-weight: 500;

      .btn {
        width: 46rem;
        font-size: 15rem;
        font-weight: 400;
        color: #455A64;
      }
    }

    .content {
      height: calc(60vh - 99rem);
      width: 100vw;
      display: flex;
      align-items: center;
      flex-direction: column;
      overflow: scroll;

      .cord_box {
        &:active {
          background-color: var(--lr_active_bgc);
        }

        width: 100vw;
        height: 40rem;
        min-height: 40rem;
        padding-top: 8rem;
        padding-bottom: 8rem;
        display: flex;
        align-items: center;
        border-bottom: 1rem solid #efefef;

        .box_r {
          height: 36rem;
          width: 36rem;
          border-radius: 8rem;
          // background-color: ;
          margin-left: 15rem;
          margin-right: 15rem;
          line-height: 36rem;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          color: var(--cart_bg_color);
          font-size: 13rem;
          font-weight: 600;
        }

        .box_m {
          height: 40rem;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: flex-start;
          max-width: calc(100vw - 81rem);

          .m_top {
            height: fit-content;
            text-align: left;
            font-size: 14rem;
            width: calc(100vw - 81rem);
          }

          .m_bot {
            width: calc(100vw - 81rem);
            height: fit-content;
            font-size: 12rem;
            color: #B0BEC5;
            display: flex;
            justify-content: space-between;
          }
        }
      }

      .noborder {
        border: none !important;
      }

      .swcr {
        width: 60rem;
        height: 40rem;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 500;
        padding-top: 8rem;
        padding-bottom: 8rem;
        color: red;
      }
    }
  }
}
</style>